<script setup>
import {
    Search,
    Edit,
    Delete
} from '@element-plus/icons-vue'
import { ref } from 'vue'
import { articleHeatService,articleCountService,articleListService, articleAddService, articleUpdateService, articleDeleteService } from '@/api/article';
import { getHidAndComment, HitUpdateService, CommentsUpdateService, statisticListService } from '@/api/statistic';
import { ElMessage, ElMessageBox } from 'element-plus'
const article = ref([
    {
        id: 2,
        title: "securit入门",
        category: "编程",
        hit: "12",
        thumbnail: "http://sem8jxmog.hn-bkt.clouddn.com/ee2b1290-5591-4063-a15a-df394e1cf921.png",
        createTime: "2023-09-02 12:06:59",
    },
    {
        id: 2,
        title: "securit入门",
        category: "编程",
        hit: "12",
        thumbnail: "http://sem8jxmog.hn-bkt.clouddn.com/ee2b1290-5591-4063-a15a-df394e1cf921.png",
        createTime: "2023-09-02 12:06:59",
    },
    {
        id: 2,
        title: "securit入门",
        category: "编程",
        hit: "12",
        thumbnail: "http://sem8jxmog.hn-bkt.clouddn.com/ee2b1290-5591-4063-a15a-df394e1cf921.png",
        createTime: "2023-09-02 12:06:59",
    },
    {
        id: 2,
        title: "securit入门",
        category: "编程",
        hit: "12",
        thumbnail: "http://sem8jxmog.hn-bkt.clouddn.com/ee2b1290-5591-4063-a15a-df394e1cf921.png",
        createTime: "2023-09-02 12:06:59",
    }
])
//分页条数据模型
const pageNum = ref(1)//当前页
const total = ref(20)//总条数
const pageSize = ref(3)//每页条数

//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
    // 将获取文章数据需要的参数更改为当前所需之后更新页面
    pageSize.value = size
    articleList()
}

//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
    pageNum.value = num
    articleList()
}
//导入文本框组件以及添加文章变量设置
import { Plus } from '@element-plus/icons-vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
//控制抽屉是否显示
const visibleDrawer = ref(false)
// 导入token
import { useTokenStore } from '@/stores/token.js'
const tokenStore = useTokenStore();
// 给文章获取所有数据绑定接口事件
const articleList = async () => {
    let params = {
        pageNum: pageNum.value,
        pageSize: pageSize.value,
    }
    let result = await articleListService(params);
    console.log(result)
    total.value = result.data.total;
    article.value = result.data.items;
    //对每篇文章进行其浏览量的查询
    for (let i = 0; i < article.value.length; i++) {
        //遍历拿到的文章列表，然后拿到文章id，然后便可以得到文章统计数据
        let art = article.value[i];
        console.log("遍历拿到的文章id:"+art.id);
        let statistic = await getHidAndComment(art.id);
        // 拿到统计数据之后将其赋值给文章列表中的hit
        article.value[i].hit = statistic.data.hit;
        console.log("遍历前拿到的文章浏览量:"+statistic.data.hit);
        console.log("遍历后拿到的文章浏览量:"+article.value[i].hit);
    }
}
//进行渲染列表数据
articleList()
//添加表单数据模型
const articleModel = ref({
    id: '',
    title: '',
    content: '',
    category: '',
    thumbnail: '',
    tag: ''
})

//绑定设置文件上传成功后调用的回调函数
const successUpload = (result) => {
    // 将调用文件上传功能接口成功后返回的文件路径置给文章图像路径
    articleModel.value.thumbnail = result.data;
}
//绑定操作标题
const title = ref('')
// 绑定回显数据事件
const showDiagor = (row) => {
    console.log("拿到的目录信息："+row.id);
    // 修改操作标题
    title.value = '修改文章'
    // 弹出操作框
    visibleDrawer.value = true;
    //进行数据回显赋值
    articleModel.value.title = row.title;
    articleModel.value.category = row.category;
    articleModel.value.thumbnail = row.thumbnail;
    articleModel.value.content = row.content;
    articleModel.value.tag = row.tag;
    // 修改的话记得将id也进行回显
    articleModel.value.id = row.id;
}
//定义编辑文章事件
const articleUpdate = async () => {
    let result = await articleUpdateService(articleModel.value);
    // 修改成功之后弹出成功提示
    ElMessage.success(result.message ? result.message : '修改成功！');
    // 刷新页面数据
    articleList();
    // 退出弹框
    visibleDrawer.value = false;
}
// 定义清空输入信息
const clearArticleModel = () => {
    articleModel.value = {
        id: '',
        title: '',
        category: '',
        thumbnail: '',
        // 这里有点疑点，将content置空字符串不行，但是给加一个空格可以
        content: ' ',
    }
}
import { useRouter } from 'vue-router';
const router = useRouter();
//绑定添加文章事件
const articleAdd = async () => {
    let result = await articleAddService(articleModel.value);
    ElMessage.success(result.message ? result.message : '添加成功！');
    // 刷新页面数据
    articleList();
    // 退出弹框
    visibleDrawer.value = false;
}
articleList();
// 定义删除文章函数
const deleteArticle = (row) => {
    ElMessageBox.confirm(
        '你确定进行对该文章的删除吗？',
        '请注意！！！',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消删除',
            type: 'warning',
        }
    )
        .then(async () => {
            //进行删除
            let result = await articleDeleteService(row.id);
            ElMessage({
                type: 'success',
                message: '删除成功！',
            })
            //更新页面数据
            articleList();
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消成功！',
            })
        })
}
// 获取跳转当前用户的详情数据页面
const show = () => {
    // router.push('/userInfoww');
}

</script>
<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>文章管理</span>
                <div class="extra">
                    <el-button type="primary"
                        @click="visibleDrawer = true; title = '添加文章'; clearArticleModel()">添加文章</el-button>
                </div>
            </div>
        </template>
        <!-- 文章列表 -->
        <el-table :data="article" style="width: 100%">
            <el-table-column label="编号" width="100" type="index"> </el-table-column>
            <el-table-column label="文章标题" prop="title"></el-table-column>
            <el-table-column label="发布时间" prop="createTime"></el-table-column>
            <el-table-column label="浏览量" prop="hit"></el-table-column>
            <el-table-column label="所属分类" prop="category"></el-table-column>
            <el-table-column label="操作" width="150">
                <template #default="{ row }">
                    <el-button :icon="Search" circle plain type="primary" @click="show(row)"></el-button>
                    <el-button :icon="Edit" circle plain type="primary" @click="showDiagor(row)"></el-button>
                    <el-button :icon="Delete" circle plain type="danger" @click="deleteArticle(row)"></el-button>
                </template>
            </el-table-column>
            <template #empty>
                <el-empty description="没有数据" />
            </template>
        </el-table>
        <!-- 分页条 -->
        <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[3, 5, 10, 15]"
            layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
            @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end" />

        <!-- 抽屉 -->
        <el-drawer v-model="visibleDrawer" :title="title" direction="rtl" size="50%">
            <!-- 添加文章表单 -->
            <el-form :model="articleModel" label-width="100px">
                <el-form-item label="文章标题">
                    <el-input v-model="articleModel.title" placeholder="请输入标题"></el-input>
                </el-form-item>
                <el-form-item label="文章分类">
                    <el-input v-model="articleModel.category" placeholder="请输入分类"></el-input>
                </el-form-item>
                <el-form-item label="文章标签">
                    <el-input v-model="articleModel.tag" placeholder="请输入标签"></el-input>
                </el-form-item>
                <el-form-item label="文章封面">
                    <el-upload class="avatar-uploader" :auto-upload="true" :show-file-list="false" action="/api/upload"
                        name="file" :headers="{ Authorization: tokenStore.token }" :on-success="successUpload">
                        <img v-if="articleModel.thumbnail" :src="articleModel.thumbnail" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="文章内容">
                    <div class="editor">
                        <quill-editor theme="snow"
                            v-model:content="articleModel.content" contentType="html">
                        </quill-editor>
                    </div>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="title == '添加文章' ? articleAdd() : articleUpdate()">发布</el-button>
                </el-form-item>
            </el-form>
        </el-drawer>
    </el-card>
</template>

<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
}

.avatar {
    max-width: 220px;
}

/* 抽屉样式 */
.avatar-uploader {
    :deep() {
        .avatar {
            width: 178px;
            height: 178px;
            display: block;
        }

        .el-upload {
            border: 1px dashed var(--el-border-color);
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            transition: var(--el-transition-duration-fast);
        }

        .el-upload:hover {
            border-color: var(--el-color-primary);
        }

        .el-icon.avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            text-align: center;
        }
    }
}
.editor {
    width: 100%;

    :deep(.ql-editor) {
        min-height: 200px;
    }
}
</style>